//
//  Sponsor.m
//  SHPE Conference Companion
//
//  Created by Richard Kirk on 4/2/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Sponsor.h"
#import "Conference.h"
#import "SponsorshipLevel.h"


@implementation Sponsor
@dynamic thumbnailURL;
@dynamic website;
@dynamic id;
@dynamic recruiting;
@dynamic acceptingInternationalStudents;
@dynamic thumbnailData;
@dynamic name;
@dynamic conference;
@dynamic level;
@synthesize parent;

@synthesize xmlParser, xmlStringBuilder;

-(id)initWithParser:(NSXMLParser *)parser attributeDict:(NSDictionary *)attributes parent:(id)parentObject
{   
    
    [super initWithEntity:[NSEntityDescription entityForName:@"Sponsor" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [parser setDelegate:self];
    [self setParent:parentObject];
    
    
    self.id = [NSNumber numberWithInt:[[attributes objectForKey:@"id"] intValue]];
    self.name = [NSString stringWithString:[attributes objectForKey:@"name"]];
    self.thumbnailURL = [NSString stringWithString:[attributes objectForKey:@"xlink:logo"]];
    self.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.thumbnailURL]];
    
    
    return self;
    
}

-(id)initWithSponsorId:(int)sponsorId
{
    
    [super initWithEntity:[NSEntityDescription entityForName:@"Sponsor" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];
    
    xmlParser = [NSXMLParser alloc];
    xmlParser.delegate = self;
    
    [xmlParser initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://openshpe.staging.shpe.org/conference/v1/sponsor/%d", sponsorId]]];    
    
    if (xmlParser){
        [xmlParser parse];
    }
    
    
    return self;
}

-(NSString *)description
{
    
    
    return [NSString stringWithFormat:@"\nSponsorid : %@\nName : %@\nRecruiting : %@\nAccepting International students :  %@\nWebsite : %@\n", self.id, self.name, self.recruiting, self.acceptingInternationalStudents, self.website];
    
}



- (void)addConferenceObject:(Conference *)value {    
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"conference" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"conference"] addObject:value];
    [self didChangeValueForKey:@"conference" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)removeConferenceObject:(Conference *)value {
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"conference" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"conference"] removeObject:value];
    [self didChangeValueForKey:@"conference" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)addConference:(NSSet *)value {    
    [self willChangeValueForKey:@"conference" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"conference"] unionSet:value];
    [self didChangeValueForKey:@"conference" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
}

- (void)removeConference:(NSSet *)value {
    [self willChangeValueForKey:@"conference" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"conference"] minusSet:value];
    [self didChangeValueForKey:@"conference" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
}




- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{
    
    if ( ( [elementName isEqualToString:@"conference-sponsor"] )) {
        self.id = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
        self.name = [NSString stringWithString:[attributeDict objectForKey:@"name"]];
        self.thumbnailURL = [NSString stringWithString:[attributeDict objectForKey:@"xlink:logo"]];
        self.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.thumbnailURL]];
        return;
    }
    
    if ( ( [elementName isEqualToString:@"level"] )) {
        NSFetchRequest *sponsorshipRequest = [[[NSFetchRequest alloc] init] autorelease];
        [sponsorshipRequest setEntity:[NSEntityDescription entityForName:@"SponsorshipLevel" inManagedObjectContext:[self managedObjectContext]]];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id = %d)",[[attributeDict objectForKey:@"id"] intValue]];
        
        [sponsorshipRequest setPredicate:predicate];
        [sponsorshipRequest setSortDescriptors:nil];
        
        NSArray *sponsorshipLevelObjectArray = [[self managedObjectContext] executeFetchRequest:sponsorshipRequest error:nil];
        if([sponsorshipLevelObjectArray lastObject])
        {
            [self setLevel:[sponsorshipLevelObjectArray lastObject]];
        }
        else 
            NSLog(@"Sponsorship Level request returned nil\n",nil);
        return;
        
    }
    if ( ( [elementName isEqualToString:@"conference"] )) {
        
        /* I need to add a section here to link the Conference level */
            // Maybe not beause I am initing this from the conference 
            // [self addConferenceObject:[NSEntityDescription ]
        
        return;
    }
    
    
}



- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{   string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@" & "];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    if (!xmlStringBuilder) {
        xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
    }
    
    [xmlStringBuilder appendString:string];
    
    
}

-(void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString
{    
    
        //Didnt need this 
    /**
     
     NSLog(@"\nfound ignoreable whitespace: whitespace string: \"%@\"\n", whitespaceString);
     if (!xmlStringBuilder) {
     xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
     
     }
     //   if (whitespaceString != @"\n")
     // [xmlStringBuilder appendString:whitespaceString];
     
     */
    
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    
        // ignore root and empty elements
    if ( [elementName isEqualToString:@"conference-sponsor"] ) {
        [parser setDelegate:parent];
        xmlStringBuilder = nil;
        return;
    }
    
    else if( ([elementName isEqualToString:@"sponsorship"]) ||
            ( [elementName isEqualToString:@"recruiting-info"]))
        return;
    
    
    else if( [elementName isEqualToString:@"website"] ) {
        
        self.website =[NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"recruiting"] ) {
        self.recruiting = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"accepts-international-students"] ) {
        self.acceptingInternationalStudents = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    xmlStringBuilder = nil;
    
    
    
}



-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    
    NSLog(@"XML ERROR :\n%@\n",[parseError description]);
    
    UIAlertView *parserAlert = [[UIAlertView alloc]init];
    
    
    [parserAlert setTitle:@"Parsing Error!"];
    
    [parserAlert setMessage:[NSString stringWithFormat:@"Error %i, Description: %@, Line: %i, Column: %i", 
                             [parseError code], 
                             [parseError localizedDescription], 
                             [parser lineNumber], 
                             [parser columnNumber]]];
    
    [parserAlert addButtonWithTitle:@"OK"];
    [parserAlert show];
    [parserAlert release];
    
    
    
}




@end
